package com.fametal.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.fametal.R;
import com.fametal.GlobalConstant.Settings;
import com.fametal.ui.utils.DialogUtils;
import com.fametal.ui.utils.ThreadPool;
import com.fametal.ui.utils.Utils;

public class LoginActivity extends Activity implements OnClickListener {

	private Button login;
	private ProgressBar progress;
	private TextView text;
	private final int tblRelayDelay[] = {
		5,
		15,
		25,
		35,
		45,
		95,
	};
	
	private final String tblRelayNo[] = {
			"0",
			"1",
			"4",
			"3",
			"5",
			"2"
	};

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			progress.setProgress(msg.arg1);
			
			for(int i=0;i<6;i++){
				if(msg.arg1 == tblRelayDelay[i]){
					String url = Settings.IP + "cgi-bin/relay_control.cgi?relayNo=" + tblRelayNo[i]+"&relayStatus=1";
					Utils.get(getParent(), url, false);
					break;
				}
			}
			if(msg.arg1 == 100){
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), MainControlActivity.class);
				startActivity(intent);
				finish();
			}
		};
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.login_system);

		login = (Button) findViewById(R.id.login);
		progress = (ProgressBar) findViewById(R.id.process);
		text = (TextView) findViewById(R.id.wait);

		login.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if(!Utils.isConnected(this)){
			DialogUtils.alert(this, "提示", "当前网络不可用，请检查网络!", null);
			return;
		}
		login.setVisibility(View.INVISIBLE);
		progress.setVisibility(View.VISIBLE);
		text.setVisibility(View.VISIBLE);

		ThreadPool.excuteLongTask(new Runnable() {
			@Override
			public void run() {
				int num = 0;
				while (num <= 100) {
					Message msg = new Message();  
					msg.arg1 = num;  
					handler.sendMessage(msg); 
					num++;
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});
	}
}
